package com.sne.sys.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sne.common.entity.Result;
import com.sne.sys.dto.SysDictDTO;
import com.sne.sys.entity.SysDict;
import com.sne.sys.service.ISysDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.List;

/**
 * <p>
 * 字典管理 前端控制器
 * </p>
 *
 * @author fanghh
 * @since 2020-01-10
 */
@Slf4j
@RestController
@RequestMapping("/sys/sys-dict")
@Api(tags = "字典管理")
public class SysDictController {

    @Autowired
    private ISysDictService iSysDictService;

    @PreAuthorize("hasAuthority('sys:dict:page')")
    @ApiOperation(value = "字典列表")
    @PostMapping("/page")
    public Result page(Page page, @RequestBody SysDictDTO dict) {
        return Result.success(iSysDictService.findPage(page, dict));
    }

    @CacheEvict(value = "sys-dict",key = "#{dict.dictCode}")
    @PreAuthorize("hasAuthority('sys:dict:save')")
    @ApiOperation(value = "保存字典组")
    @PostMapping("/save")
    public Result save(@Valid @RequestBody SysDict dict) {
        if (!iSysDictService.checkDictUnique(dict)) {
            return Result.failed("字典编号已存在", null);
        }
        return Result.success(iSysDictService.save(dict));
    }

    @CacheEvict(value = "sys-dict",key = "#dict.dictCode")
    @PreAuthorize("hasAuthority('sys:dict:update')")
    @ApiOperation(value = "更新字段组")
    @PutMapping("/update")
    public Result update(@Valid @RequestBody SysDict dict) {
        if (!iSysDictService.checkDictUnique(dict)) {
            return Result.failed("字典编号已存在", null);
        }
        return Result.success(iSysDictService.updateById(dict));
    }

    @PreAuthorize("hasAuthority('sys:dict:delete')")
    @ApiOperation(value = "删除字典组")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id) {
        return Result.success(iSysDictService.deleteDict(id));
    }

    @ApiOperation(value = "获取字典组")
    @GetMapping("/find/{id}")
    public Result find(@PathVariable("id") Long id) {
        return Result.success(iSysDictService.getById(id));
    }

    @PreAuthorize("hasAuthority('sys:dict:deleteIds')")
    @ApiOperation(value = "批量删除字典组")
    @DeleteMapping("/deleteIds")
    public Result deleteIds(@RequestBody @Size(min = 1, message = "ids不能为空") List<Long> ids) {
        return Result.success(iSysDictService.removeByIds(ids));
    }

}

